package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	@Override
	public IPage<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> detailPage, Long userId) {
		//	select * from user_account_detail where user_id = ? and trade_type = 1204 and is_deleted = 0;
		LambdaQueryWrapper<UserAccountDetail> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(UserAccountDetail::getUserId,userId).eq(UserAccountDetail::getTradeType,SystemConstant.ACCOUNT_TRADE_TYPE_MINUS).orderByDesc(UserAccountDetail::getCreateTime);
		return userAccountDetailMapper.selectPage(detailPage,wrapper);
	}

	@Override
	public IPage<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> detailPage, Long userId) {
		//	select * from user_account_detail where user_id = ? and trade_type = 1201 and is_deleted = 0;
		LambdaQueryWrapper<UserAccountDetail> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(UserAccountDetail::getUserId,userId).eq(UserAccountDetail::getTradeType,SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT).orderByDesc(UserAccountDetail::getCreateTime);
		return userAccountDetailMapper.selectPage(detailPage,wrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rechargePaySuccess(String orderNo) {
		//	修改 recharge_info.recharge_status; user_account.total_amount;available_amount; user_account_detail-记录账户变化
		//	根据orderNo 查询Recharge对象
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo,orderNo));
		if( null != rechargeInfo){
			//	修改 recharge_info.recharge_status; user_account.total_amount;available_amount; user_account_detail-记录账户变化
			//	修改 recharge_info.recharge_status;
			rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
			rechargeInfoMapper.updateById(rechargeInfo);
			//	修改 user_account.total_amount;available_amount;
			userAccountMapper.updateAmount(rechargeInfo.getRechargeAmount(),rechargeInfo.getUserId());
			//	记录当前账户资金变化
			this.addUserAccountDetail(rechargeInfo.getUserId(),"充值成功:"+rechargeInfo.getRechargeAmount(), SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(),orderNo);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long checkAndDeduct(AccountDeductVo accountDeductVo) {
		//	执行检查与扣减金额
		try {
			//	这是正常
			Long count = userAccountMapper.checkAndDeduct(accountDeductVo.getAmount(), accountDeductVo.getUserId());
			//	记录当前账户变动; user_account_detail
			this.addUserAccountDetail(accountDeductVo.getUserId(),accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(),accountDeductVo.getOrderNo());
			return count;
		} catch (Exception e) {
			//	这是异常
			return 0l;
		}

	}

	/**
	 * 添加账户变动信息
	 * @param userId
	 * @param title
	 * @param tradeType
	 * @param amount
	 * @param orderNo
	 */
	private void addUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
		//	创建账户明细对象
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetailMapper.insert(userAccountDetail);
	}

	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		//	select available_amount from user_account where user_id = ?
		return userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId,userId)).getAvailableAmount();
	}

	@Override
	public void initUserAccount(Long userId) {
		//	创建对象
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		userAccount.setTotalAmount(new BigDecimal("1000"));
		userAccount.setAvailableAmount(new BigDecimal("1000"));
		userAccountMapper.insert(userAccount);
	}
}
